/*
 * Main.java
 *
 * Created on January 20, 2007, 3:06 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package ca.uvic.group2.testHarness;
import java.io.*;
//import javax.swing.*;
import java.util.*;
import java.net.*;
import org.apache.log4j.*;

/**
 *
 * @author pat
 */
public class Main {

   private static Category debugLog = Logger.getInstance("TestHarnessDebug");
   private static int commandCounter = 0;
   private static boolean pleaseQuit = false;

   public static synchronized void countCommand() {
      commandCounter++;
   }//endMethod

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        debugLog.info("Starting TestHarness");
        String filename, nextLine, uname;
        HashMap outFiles = new HashMap();
        LinkedList threadList = new LinkedList();
        StringTokenizer sToken;
        int fileCount = 0;
        BufferedWriter out;
        long startTime, endTime;
        WSConnectionManager connManager = new WSConnectionManager();
        int timeToQuit = 0;
        boolean isRemote = false;

        filename = "test.txt";
        if (args.length > 0) {
            if (args[0].equals("--remote")) {
                isRemote = true;
                filename = args[1];
                if (args.length > 2) {
                    timeToQuit = Integer.parseInt(args[2]);
                }
            } else {
                filename = args[0];
                if(args.length > 1)
                    timeToQuit = Integer.parseInt(args[1]);
            }
        }

        if(filename == null) {
            debugLog.debug("Command Format: java Main <filename>");
            System.exit(0);
        }

        debugLog.debug("Runing file: " + filename);

        //Initalize System
        if (!isRemote) {
            System.out.println("INIT");
            debugLog.info("Initalizing System");
            connManager.commandInit();
            debugLog.info("Init complete");
            System.out.println("INIT COMPELTE");
        }

        String[] filenames;

        System.out.println("Parseing Inputfiles into User files");
        if(!isRemote && filename.toLowerCase().contains("1000user_testworkload")) {
            System.out.println("Using 1000 user tricks");
            filenames = DistributeTest.initBreakUp(filename, outFiles, 20);
        } else {
            filenames = DistributeTest.userPerFile(filename, outFiles, isRemote);
        }

        debugLog.info("User files complete.");
        debugLog.info("Starting UserThreads");

        //Web host decision
        //Random gen = null;
        LinkedList l = null;
        String host = System.getProperty("group2.tomcatHost", "localhost");
        StringTokenizer sToken2 = new StringTokenizer(host, ",");
	// gen = new Random(System.currentTimeMillis());
        l = new LinkedList();

        int serverCount = 0;
        while(sToken2.hasMoreTokens()) {
           l.add(sToken2.nextToken());
           serverCount++;
        }


        //String host = System.getProperty("group2.tomcatHost", "localhost");
        System.out.println("Server count is  " + serverCount);
        //Start Timer for Test run.
        startTime = System.currentTimeMillis();
        for(int i = 1; i <= filenames.length; i++) {
            UserThread userComm = new UserThread(filenames[i-1], timeToQuit,
                  (String) l.get((i-1) % serverCount));
            userComm.start();
            threadList.add(userComm);
        }//end For

        Iterator i = threadList.iterator();
        while(i.hasNext()) {
            UserThread ut = (UserThread) i.next();
            try {
                ut.join();
            } catch (InterruptedException ignored) {
            }
        }//endWhile

        debugLog.info("UserThreads Completed");

        if (!isRemote) {
            //Get Dumplog
            debugLog.info("Dumplog Call");
            new WSConnectionManager().commandStopStats();
            new WSConnectionManager().commandDumplog();
            commandCounter++;
        }

        //End Timer
        endTime = System.currentTimeMillis();

        //Print Stats
        System.out.println("Number of transactions: " + commandCounter);
        System.out.println("Time to Complete: " + (endTime - startTime)/1000.0);
        System.out.println("Transaction per Second: " + commandCounter*1000.0/(endTime - startTime));

        debugLog.info("Test Harness Complete");
    }//end Method

}//end Class
